#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include "InetAddr.hpp"
#include "Log.hpp"

using namespace std;

void Usage(string proc)
{
    cout << "Usage: " << proc << " + ip + port" << endl;
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip = argv[1];
    uint16_t serverport = stoi(argv[2]);

    // 创建套接字
    int sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        cout << "sock error" << endl;
        exit(1);
    }

    // 要bind, 但不能显示bind
    // 填充结构体信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    // 发起连接
    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server));
    if (n < 0)
    {
        cout << "connect error" << endl;
        exit(2);
    }

    // 
    while(true)
    {
        cout << "Please echo# ";
        string outstring;
        getline(cin, outstring);
        ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0);// write
        if(s > 0)
        {
            char inbuffer[1024];
            ssize_t m = recv(sockfd, inbuffer, sizeof(inbuffer)-1, 0); // read
            if(m > 0)
            {
                inbuffer[m] = 0;
                cout << inbuffer << endl;
            }
            else 
            {
                break;
            }
        }
        else 
        {
            break;
        }
    }

    close(sockfd);
    return 0;
}